package com.github.hgkmail.hello.leetcode101.base;

import com.google.common.base.Splitter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.out;

public class IOUtil {

    /**
     * 从txt文件读取数据，外面的list是行，里面的list是列（空格分隔）
     * @param fileName
     * @return
     */
    public static List<List<String>> readTxt(String fileName) {
        List<List<String>> results = new ArrayList<>();
        File file = new File(fileName);
        if (!file.exists()) {
            System.err.println("File doesn't exist: "+fileName);
            return results;
        }
        try {
            List<String> lines = IOUtils.readLines(new FileInputStream(file), StandardCharsets.UTF_8);
            if (CollectionUtils.isEmpty(lines)) {
                return results;
            }
            for (String line : lines) {
                List<String> cols = Splitter.on(" ").omitEmptyStrings().trimResults().splitToList(line);
                if (CollectionUtils.isNotEmpty(cols)) {
                    results.add(cols);
                }
            }
            out.println("read successfully, lines: "+results.size());
            return results;
        } catch (IOException e) {
            System.err.println("error: "+e.getMessage());
            return results;
        }
    }

    public static void printTxt(List<List<String>> data) {
        for (List<String> line:data) {
            for (String col:line) {
                out.print(col);
                out.print(" ");
            }
            out.println();
        }
    }

    public static void main(String[] args) {
        List<List<String>> data = readTxt("/Users/hgkmail-mb/github/hello-spring-boot-app/src/main/resources/tinyG.txt");
        printTxt(data);
        out.println("end");
    }

}
